﻿Imports System.IO

Namespace myBookmarks.Web
    ''' <summary>
    ''' Render view to string  
    ''' Original Source:  http://stackoverflow.com/questions/483091/render-a-view-as-a-string/1241257#1241257
    ''' </summary>
    Public Module ControllerExtensions
        <System.Runtime.CompilerServices.Extension()> _
    Public Function RenderViewToString(ByVal controller As Controller, ByVal viewName As String, ByVal viewData As Object) As String
            'Create memory writer
            Dim sb = New StringBuilder()
            Dim memWriter = New StringWriter(sb)

            'Create fake http context to render the view
            Dim fakeResponse = New HttpResponse(memWriter)
            Dim fakeContext = New HttpContext(HttpContext.Current.Request, fakeResponse)
            Dim fakeControllerContext = New ControllerContext(New HttpContextWrapper(fakeContext), controller.ControllerContext.RouteData, controller.ControllerContext.Controller)

            Dim oldContext = HttpContext.Current
            HttpContext.Current = fakeContext

            'Use HtmlHelper to render partial view to fake context
            Dim html = New HtmlHelper(New ViewContext(fakeControllerContext, New FakeView(), New ViewDataDictionary(), New TempDataDictionary()), New ViewPage())
            html.RenderPartial(viewName, viewData)

            'Restore context
            HttpContext.Current = oldContext

            'Flush memory and return output
            memWriter.Flush()
            Return sb.ToString()
        End Function
        Public Class FakeView
            Implements IView
#Region "IView Members"

            Public Sub Render(ByVal viewContext As ViewContext, ByVal writer As System.IO.TextWriter) Implements IView.Render
                Throw New NotImplementedException()
            End Sub

#End Region
        End Class
    End Module
End Namespace